package com.woyou.ui.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.woyou.Constant;
import com.woyou.bean.Info;
import com.woyou.bean.OrderDetail;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.OrderDefaultReq;
import com.woyou.bean.rpc.SendOrderReq;
import com.woyou.service.NetWorkCenter;
import com.woyou.service.pay.PayConfig;
import com.woyou.service.pay.PayManger;
import com.woyou.service.pay.PayManger.IPayCallback;
import com.woyou.service.pay.PayManger.Type;
import com.woyou.ui.activity.orderdetail.OrderDetailActivity;
import com.woyou.ui.activity.orderlist.MyOrderActivity;
import com.woyou.utils.LogUtil;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.eventbus.EventRestConfirm;

import de.greenrobot.event.EventBus;

/**
 * 在线支付
 * 
 * @author zhou
 *
 */
public class PayOnlineActivity extends BaseActivity {

	private static final String TAG = "PayOnlineActivity";
	public static final int NOTIFY = 0x100;

	private TextView downTimeText;
	private TextView payMoneyText;
	private TextView shopNameText;
	private TextView orderIdText;
	private ImageView alipayImage;
	private ImageView weixinpayImage;
	private int payType = 1;
	private boolean flag = false;

	private SendOrderReq mOrderReq;
	private String mOrderid;
	private String mPhone;
	private String mName;// 店铺名称
	private float totle;// 支付总价

	private long mTime;
	private Timer mTimer;
	private TimerTask timerTask;

	private PayManger payManger;
	@SuppressWarnings("rawtypes")
	private Class origin;

	private OrderDetail mOrderDetail;

	private IPayCallback mPayCallback;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay_order);
		initView();
		initEvent();
		getData();
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, "onResume");
		if (flag) {
			dismissProgressDialog();
			flag = false;
		}
		payManger = new PayManger(PayOnlineActivity.this);
		mPayCallback = new IPayCallback() {

			@Override
			public void onSucced() {

				dismissProgressDialog();
				flag = false;
				runOnUI(new Runnable() {

					@Override
					public void run() {
						Map<String, Object> map = new HashMap<String, Object>();
						Info<Map<String, Object>> info = new Info<Map<String, Object>>(map);
						if (origin != null && origin.getName().equals(ConfirmOrderActivity_.class.getName())) {
							map.put("req", mOrderReq);
							map.put("orderid", mOrderid);
							map.put("phone", mPhone);
						} else {
							// mOrderDetail;//待确认界面
							map.put("orderid", mOrderDetail.getoId());
							map.put("phone", mOrderDetail.getsName());
						}
						map.put("type", payType);
						map.put("price", totle);
						openActivity(OrderStatusActivity_.class, info);

						mTimer.cancel();
						downTimeText.setText("已完成支付，不允许重复支付！");
						findViewById(R.id.pay_confirm).setEnabled(false);
						finish();
					}
				});

			}

			@Override
			public void onError(final int error) {
				flag = false;
				runOnUI(new Runnable() {

					@Override
					public void run() {
						if (error == PayConfig.PAY_NOT_CLIENT) {
							showToastOnUI("未找到微信客户端，请安装微信客户端后再使用微信支付！");
						} else {
							showToast("支付失败，请尝试重新支付！");
						}
						dismissProgressDialog();
					}
				});

			}
		};
		startCountTime();

		loadOrderDetail(mOrderid);
	}

	private void startCountTime() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;

			timerTask.cancel();
			timerTask = null;
		}

		timerTask = new TimerTask() {

			@Override
			public void run() {
				mTime = mTime - 1000;
				mHandler.sendEmptyMessage(NOTIFY);
			}
		};

		mTimer = new Timer();
		mTimer.schedule(timerTask, 0, 1000);
	}

	@SuppressWarnings({ "unchecked" })
	private void getData() {
		if (hasInfo()) {
			origin = mInfo.getOriginClzz();
			if (origin != null && origin.getName().equals(ConfirmOrderActivity_.class.getName())) {
				// 确认订单界面
				Map<String, Object> data = (Map<String, Object>) mInfo.getData();
				mOrderReq = (SendOrderReq) data.get("req");
				mOrderid = (String) data.get("orderid");
				mPhone = (String) data.get("phone");
				mName = (String) data.get("name");
				mTime = 30 * 60 * 1000;
				totle = mShoppingCarModel.getTotalCost();

			} else if (origin != null && (origin.getName().equals(OrderDetailActivity.class.getName())
					|| origin.getName().equals(MyOrderActivity.class.getName()))) {
				// 订单详情界面、订单列表界面
				mOrderDetail = (OrderDetail) mInfo.getData();
				mOrderid = mOrderDetail.getoId();
				mPhone = mOrderDetail.getsPhone();
				mName = mOrderDetail.getsName();
				mTime = (long) mOrderDetail.getInvalidTime() * 1000;
				totle = Float.parseFloat(mOrderDetail.getTotalPrice());
			}
			LogUtil.d("TAG", "price:" + totle);
			payMoneyText.setText("￥" + ParseUtils.formatPrice(totle));
			orderIdText.setText(mOrderid);
			shopNameText.setText(mName);
		}
	}

	private void initView() {
		TextView titleText = (TextView) findViewById(R.id.head_title);
		titleText.setText("支付订单");
		downTimeText = (TextView) findViewById(R.id.pay_time);
		payMoneyText = (TextView) findViewById(R.id.pay_money);
		shopNameText = (TextView) findViewById(R.id.pay_shopname);
		orderIdText = (TextView) findViewById(R.id.pay_orderid);
		alipayImage = (ImageView) findViewById(R.id.alipay_image);
		weixinpayImage = (ImageView) findViewById(R.id.weixinpay_image);
	}

	private void initEvent() {
		findViewById(R.id.myback).setOnClickListener(this);
		findViewById(R.id.alipay).setOnClickListener(this);
		findViewById(R.id.weixinpay).setOnClickListener(this);
		findViewById(R.id.pay_confirm).setOnClickListener(this);
	}

	/**
	 * 加载订单详情
	 * 
	 * @param oId
	 */
	public void loadOrderDetail(final String oId) {
		if (!NetWorkCenter.isNetworkConnected(getContext())) {
			showToast("请检查您的网络!");
			return;
		}

		executeTask(new Runnable() {

			@Override
			public void run() {
				try {
					UserInfo info = mUserModel.getUserInfo();
					OrderDefaultReq orderDefaultReq = new OrderDefaultReq();
					orderDefaultReq.setoId(oId);
					orderDefaultReq.setuId(info.getuId());
					orderDefaultReq.setPwd(info.getPwd());
					final Result<OrderDetail> result = mOrderModel.v2_3queryOrderDetail(orderDefaultReq);
					runOnUI(new Runnable() {

						@Override
						public void run() {
							if (result != null && result.getCode() == 1) {
								mOrderDetail = result.getData();
								mOrderid = mOrderDetail.getoId();
								mPhone = mOrderDetail.getsPhone();
								mName = mOrderDetail.getsName();
								mTime = (long) mOrderDetail.getInvalidTime() * 1000;
								totle = Float.parseFloat(mOrderDetail.getTotalPrice());
								LogUtil.d(TAG, "mTime:" + mTime + " mPhone:" + mPhone + " totle:" + totle);
								
								payMoneyText.setText("￥" + ParseUtils.formatPrice(totle));
								orderIdText.setText(mOrderid);
								shopNameText.setText(mName);

							}
						}
					});

				} catch (RetrofitError e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.myback:
			backOperate();
			break;

		case R.id.alipay:
			alipayImage.setImageResource(R.raw.rediobox1);
			weixinpayImage.setImageResource(R.raw.rediobox2);
			payType = Constant.ALIPAY;
			break;

		case R.id.weixinpay:
			alipayImage.setImageResource(R.raw.rediobox2);
			weixinpayImage.setImageResource(R.raw.rediobox1);
			payType = Constant.WEIXIN;
			break;

		case R.id.pay_confirm:
			// 确认支付
			showProgressDialog("正在支付，请稍后...", false);
			Type type;
			if (payType == 2) {
				type = Type.WEIXIN;
			} else {
				type = Type.ALIPAY;
			}
			flag = true;
			payManger.onlinePay(mPayCallback, mName, totle, mOrderid, type);
			break;

		default:
			break;
		}
	}

	@Override
	public boolean backOperate() {
		// 清空购物车
		mShoppingCarModel.clearShopppingCar();
		// 重置确认订单页面
		EventBus.getDefault().post(new EventRestConfirm());

		Info<String> info = new Info<String>(mOrderid);
		info.setOrigin(PayOnlineActivity.class);
		openActivity(OrderDetailActivity.class, info);
		finish();
		return true;
	}

	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat format = new SimpleDateFormat("mm分ss秒");

	private Handler mHandler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == NOTIFY) {
				// 30分钟超时
				// if (mTime <= 1000 && mTime>0) {
				// downTimeText.setText("支付超时，请重新下单！");
				// downTimeText.setTextColor(Color.RED);
				// mTimer.cancel();
				// findViewById(R.id.pay_confirm).setEnabled(false);
				//
				// AlertDialog dialog = null;
				// Builder builder = new AlertDialog.Builder(mContext);
				// builder.setTitle("提示");
				// builder.setMessage("订单已取消，请重新下单!");// 设置信息
				// builder.setCancelable(true);
				//
				// builder.setPositiveButton("确定", new
				// DialogInterface.OnClickListener() {// 设置监听事件
				// @SuppressWarnings("rawtypes")
				// public void onClick(DialogInterface dialog, int which) {
				// Info<Class> info = new Info<Class>();
				// info.setData(ShopsFragment_.class);
				// openActivity(HomeActivity_.class, info);
				// dialog.dismiss();
				// finish();
				// }
				// });
				// try {
				// if (dialog == null || !dialog.isShowing()) {
				// dialog = builder.create();// 创建对话框
				//// dialog.show();// 显示对话框
				// dialog.setCanceledOnTouchOutside(false);// 设置点击Dialog外部任意区域关
				// }
				// } catch (Exception e) {
				// e.printStackTrace();
				// }
				//
				// }
				if (mTime == 0) {
					Info<Map<String, Object>> info = new Info<Map<String, Object>>();
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("orderid", mOrderDetail.getoId());
					map.put("phone", mOrderDetail.getsName());
					map.put("type", payType);
					map.put("price", totle);
					info.setData(map);
					info.setOrigin(PayOnlineActivity.class);
					openActivity(OrderStatusActivity_.class, info);

					mTimer.cancel();
					downTimeText.setText("已完成支付，不允许重复支付！");
					findViewById(R.id.pay_confirm).setEnabled(false);
					finish();

				} else if(mTime>0 && mTime<=1000){
					Info<String> info = new Info<String>();
					info.setData(mOrderid);
					info.setOrigin(PayOnlineActivity.class);
					openActivity(OrderDetailActivity.class, info);
					finish();
					
				} else {
					downTimeText.setText("请在" + format.format(new Date(mTime)) + "之内完成支付");
				}
			}
			return false;
		}
	});

	// @Override
	// public void onSucced() {
	// dismissProgressDialog();
	// flag = false;
	// runOnUI(new Runnable() {
	//
	// @Override
	// public void run() {
	// Map<String, Object> map = new HashMap<String, Object>();
	// Info<Map<String, Object>> info = new Info<Map<String, Object>>(map);
	// if (origin != null &&
	// origin.getName().equals(ConfirmOrderActivity_.class.getName())) {
	// map.put("req", mOrderReq);
	// map.put("orderid", mOrderid);
	// map.put("phone", mPhone);
	// } else {
	// // mOrderDetail;//待确认界面
	// map.put("orderid", mOrderDetail.getoId());
	// map.put("phone", mOrderDetail.getsName());
	// }
	// map.put("type", payType);
	// map.put("price", totle);
	// openActivity(OrderStatusActivity_.class, info);
	//
	// mTimer.cancel();
	// downTimeText.setText("已完成支付，不允许重复支付！");
	// findViewById(R.id.pay_confirm).setEnabled(false);
	// finish();
	// }
	// });
	//
	// }

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}
	}

	// @Override
	// public void onError(final int error) {
	// flag = false;
	// runOnUI(new Runnable() {
	//
	// @Override
	// public void run() {
	// if (error == PayConfig.PAY_NOT_CLIENT) {
	// showToastOnUI("未找到微信客户端，请安装微信客户端后再使用微信支付！");
	// } else {
	// showToast("支付失败，请尝试重新支付！");
	// }
	// dismissProgressDialog();
	// }
	// });
	// }

}
